package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.manager.utils.AuthContextUtil;
import com.atguigu.spzx.model.constant.Constant;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author：tzl
 * @Date：2024/1/24 9:59
 * @description: 登陆拦截器
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 预处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、放行option方法的操作
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        // 2、验证token：
        String token = request.getHeader("token");
        // 如果token为空，给前端返回208
        if (StringUtils.isBlank(token)) {
            responseNoLoginInfo(response);
            return false;
        }
        // 3、验证redis中的token
        String userJson = redisTemplate.opsForValue().get(Constant.USER_LOGIN + token);
        // redis中是否有该用户值，没有返回208，有就封装进threadLocal中
        if (StringUtils.isBlank(userJson)) {
            responseNoLoginInfo(response);
            return false;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        // 4、存储user进threadLocal中
        AuthContextUtil.set(sysUser);
        // 放行
        return true;
    }

    /**
     * 响应后的动作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除user信息
        AuthContextUtil.remove();
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
